<?php
/* 
 * Code by Dang Chi Thao
 * Object User()
 */
class User extends DataMapper
{
    
    var  $validation = array(
        array(
            'field' => 'username',
            'rules' => array('required', 'valid_email')
        ),
        array(
            'field' => 'password',
            'rules' => array('required', 'encrypt')
        )

    );


    public function _encrypt($field)
    {
        if(!empty($this->{$field}))
        {
            if(empty($this->salt))
            {
                $this->salt = md5(uniqid(rand(), true));
            }
            $this->{$field} = sha1($this->salt.$this->{$field});
        }
    }
    public function User()
    {
        parent::DataMapper();
    }

    //login - check valid username and password
    public function is_login($user, $pword)
    {
        $u = new User();
        $u->where('username', $user);
        $u->where('password', $pword)->get();
        $flag = false;
        if($u->result_count()==1)
        {
            $flag = true;
        }
        return $flag;
    }// End login

    // login_success
    public function login_success($user, $pword, $token)
    {
        $u = new User();
        $u->where("username", $user);
        $u->where("password", $pword);
        $u->where("token", $token)->get();
        $flag = false;
        if($u->result_count()==1)
        {
            $flag = true;
        }
        return $flag;
    }// End login_success

    public function login_successful($user, $pword, $token)
    {
        $u = new User();
        $u->get();
        $flag = false;
        foreach($u->all as $ur)
        {
            if($ur->username==$user && $ur->password==$pword && $ur->token==$token)
            {
                $flag = true;
            }
        }
        
        return $flag;
    }// End login_success



    // get_by_id_user
    public function get_by_id_user($user)
    {
        $u = new User();
        $u->where('username', $user)->get();
        $id = $u->id;
        return $id;
    }


    // update_token
    public function token_update($user, $token)
    {
        $u = new User();
        $u->where('username', $user);
        return $u->update('token', $token);
    }
}
